

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=light>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/set/B.svg">
  <link rel="icon" href="/img/set/B.svg">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="程守斌">
  <meta name="keywords" content="">
  
    <meta name="description" content="结构型模式（Structural Patterns）1. 适配器模式（Adapter Pattern）适配器模式（Adapter Pattern）是一种结构型设计模式，用于将一个类的接口转换成客户端所期望的另一种接口。它允许两个不兼容的接口能够一起工作。 适配器模式常用来解决以下问题：  系统需要复用一个已存在的类，但是其接口与系统所需要的接口不兼容。 不想修改现有的接口，但是需要创建一个新的类能">
<meta property="og:type" content="article">
<meta property="og:title" content="24 种设计模式-2 (Swift 5版)">
<meta property="og:url" content="https://icoobin.github.io/2023/02/25/other/24-%E7%A7%8D%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-2-Swift-5%E7%89%88/index.html">
<meta property="og:site_name" content="Bin&#39;s blog">
<meta property="og:description" content="结构型模式（Structural Patterns）1. 适配器模式（Adapter Pattern）适配器模式（Adapter Pattern）是一种结构型设计模式，用于将一个类的接口转换成客户端所期望的另一种接口。它允许两个不兼容的接口能够一起工作。 适配器模式常用来解决以下问题：  系统需要复用一个已存在的类，但是其接口与系统所需要的接口不兼容。 不想修改现有的接口，但是需要创建一个新的类能">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-02-25T04:03:44.000Z">
<meta property="article:modified_time" content="2023-02-27T05:37:58.153Z">
<meta property="article:author" content="程守斌">
<meta property="article:tag" content="设计模式">
<meta property="article:tag" content="Swift">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>24 种设计模式-2 (Swift 5版) - Bin&#39;s blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"icoobin.github.io","root":"/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"|","loop":false,"scope":["home","post"]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/set/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"0424c6a81239810100c98bd470a50118","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?0424c6a81239810100c98bd470a50118";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  



  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 38.2vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Bin&#39;s blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/banner/posts.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="24 种设计模式-2 (Swift 5版)"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-02-25 12:03" pubdate>
          2023年2月25日 中午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          13k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          107 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">24 种设计模式-2 (Swift 5版)</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="结构型模式（Structural-Patterns）"><a href="#结构型模式（Structural-Patterns）" class="headerlink" title="结构型模式（Structural Patterns）"></a>结构型模式（Structural Patterns）</h2><h3 id="1-适配器模式（Adapter-Pattern）"><a href="#1-适配器模式（Adapter-Pattern）" class="headerlink" title="1. 适配器模式（Adapter Pattern）"></a>1. 适配器模式（Adapter Pattern）</h3><p>适配器模式（Adapter Pattern）是一种结构型设计模式，用于将一个类的接口转换成客户端所期望的另一种接口。它允许两个不兼容的接口能够一起工作。</p>
<p>适配器模式常用来解决以下问题：</p>
<ol>
<li>系统需要复用一个已存在的类，但是其接口与系统所需要的接口不兼容。</li>
<li>不想修改现有的接口，但是需要创建一个新的类能够调用现有类的接口。</li>
<li>两个不兼容的类需要协同工作，但是不能直接修改它们的接口。</li>
</ol>
<p>在适配器模式中，适配器充当中间人角色，它接收来自客户端的请求并将其转换为被适配对象的请求。适配器模式可以分为两种类型：对象适配器和类适配器。对象适配器使用组合的方式连接适配器和被适配对象，类适配器使用继承的方式连接适配器和被适配对象。</p>
<p>以下是一个使用对象适配器的 Swift 5 代码示例，用于将一个高级音乐播放器的接口适配成一个简单音乐播放器的接口：</p>
<ul>
<li><p>Swift Code</p>
  <div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-comment">// 被适配的高级音乐播放器</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">AdvancedMediaPlayer</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">playVlc</span>(<span class="hljs-params">fileName</span>: <span class="hljs-type">String</span>) &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Playing vlc file. Name: <span class="hljs-subst">\(fileName)</span>&quot;</span>)
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">playMp4</span>(<span class="hljs-params">fileName</span>: <span class="hljs-type">String</span>) &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Playing mp4 file. Name: <span class="hljs-subst">\(fileName)</span>&quot;</span>)
    &#125;
&#125;

<span class="hljs-comment">// 简单音乐播放器的接口</span>
<span class="hljs-keyword">protocol</span> <span class="hljs-title class_">MediaPlayer</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">play</span>(<span class="hljs-params">audioType</span>: <span class="hljs-type">String</span>, <span class="hljs-params">fileName</span>: <span class="hljs-type">String</span>)
&#125;

<span class="hljs-comment">// 对象适配器</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MediaAdapter</span>: <span class="hljs-title class_">MediaPlayer</span> &#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> advancedMediaPlayer: <span class="hljs-type">AdvancedMediaPlayer</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">advancedMediaPlayer</span>: <span class="hljs-type">AdvancedMediaPlayer</span>) &#123;
        <span class="hljs-keyword">self</span>.advancedMediaPlayer <span class="hljs-operator">=</span> advancedMediaPlayer
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">play</span>(<span class="hljs-params">audioType</span>: <span class="hljs-type">String</span>, <span class="hljs-params">fileName</span>: <span class="hljs-type">String</span>) &#123;
        <span class="hljs-keyword">if</span> audioType <span class="hljs-operator">==</span> <span class="hljs-string">&quot;vlc&quot;</span> &#123;
            advancedMediaPlayer.playVlc(fileName: fileName)
        &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> audioType <span class="hljs-operator">==</span> <span class="hljs-string">&quot;mp4&quot;</span> &#123;
            advancedMediaPlayer.playMp4(fileName: fileName)
        &#125;
    &#125;
&#125;

<span class="hljs-comment">// 简单音乐播放器</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">AudioPlayer</span>: <span class="hljs-title class_">MediaPlayer</span> &#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> mediaAdapter: <span class="hljs-type">MediaAdapter</span>?

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">play</span>(<span class="hljs-params">audioType</span>: <span class="hljs-type">String</span>, <span class="hljs-params">fileName</span>: <span class="hljs-type">String</span>) &#123;
        <span class="hljs-keyword">if</span> audioType <span class="hljs-operator">==</span> <span class="hljs-string">&quot;mp3&quot;</span> &#123;
            <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Playing mp3 file. Name: <span class="hljs-subst">\(fileName)</span>&quot;</span>)
        &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> audioType <span class="hljs-operator">==</span> <span class="hljs-string">&quot;vlc&quot;</span> <span class="hljs-operator">||</span> audioType <span class="hljs-operator">==</span> <span class="hljs-string">&quot;mp4&quot;</span> &#123;
            mediaAdapter <span class="hljs-operator">=</span> <span class="hljs-type">MediaAdapter</span>(advancedMediaPlayer: <span class="hljs-type">AdvancedMediaPlayer</span>())
            mediaAdapter<span class="hljs-operator">?</span>.play(audioType: audioType, fileName: fileName)
        &#125; <span class="hljs-keyword">else</span> &#123;
            <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Invalid media. <span class="hljs-subst">\(audioType)</span> format not supported&quot;</span>)
        &#125;
    &#125;
&#125;</code></pre></div></li>
</ul>
<p>在上面的示例中，**<code>AdvancedMediaPlayer</code>** 是被适配的类，它的接口与 <strong><code>MediaPlayer</code></strong> 接口不兼容。**<code>MediaAdapter</code>** 是适配器，它使用组合的方式连接 <strong><code>AdvancedMediaPlayer</code></strong> 和 **<code>MediaPlayer</code>**，并将 <strong><code>AdvancedMediaPlayer</code></strong> </p>
<h3 id="2-桥接模式（Bridge-Pattern）"><a href="#2-桥接模式（Bridge-Pattern）" class="headerlink" title="2. 桥接模式（Bridge Pattern）"></a>2. 桥接模式（Bridge Pattern）</h3><p>桥接模式（Bridge Pattern）是一种结构型设计模式，用于将抽象部分与实现部分分离，使它们可以独立地变化，从而降低它们之间的耦合度。</p>
<p>桥接模式常用于需要多个不同平台、不同类型的类之间协同工作的场景，它能够通过将这些类的不同维度分离来实现这个目的，从而使得这些类可以在系统中独立地变化。</p>
<p>具体实现上，桥接模式通过在抽象层和实现层之间增加一个桥接接口（Bridge），来将抽象层和实现层分离。这个桥接接口通常包含了一些基本操作，而抽象层和实现层分别继承这个桥接接口，从而能够相互协作。</p>
<p>以下是一个使用桥接模式的 Swift 5 代码示例，其中将一个图形对象的绘制行为和图形类型进行分离：</p>
<ul>
<li><p>Swift Code</p>
  <div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-comment">// 实现层</span>
<span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Drawer</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">draw</span>(<span class="hljs-params">x</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">y</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">radius</span>: <span class="hljs-type">Double</span>)
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">CircleDrawer</span>: <span class="hljs-title class_">Drawer</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">draw</span>(<span class="hljs-params">x</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">y</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">radius</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Draw Circle at (<span class="hljs-subst">\(x)</span>, <span class="hljs-subst">\(y)</span>) with radius <span class="hljs-subst">\(radius)</span>&quot;</span>)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">SquareDrawer</span>: <span class="hljs-title class_">Drawer</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">draw</span>(<span class="hljs-params">x</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">y</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">radius</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Draw Square at (<span class="hljs-subst">\(x)</span>, <span class="hljs-subst">\(y)</span>) with radius <span class="hljs-subst">\(radius)</span>&quot;</span>)
    &#125;
&#125;

<span class="hljs-comment">// 抽象层</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Shape</span> &#123;
    <span class="hljs-keyword">let</span> x: <span class="hljs-type">Double</span>
    <span class="hljs-keyword">let</span> y: <span class="hljs-type">Double</span>
    <span class="hljs-keyword">let</span> radius: <span class="hljs-type">Double</span>
    <span class="hljs-keyword">let</span> drawer: <span class="hljs-type">Drawer</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">x</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">y</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">radius</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">drawer</span>: <span class="hljs-type">Drawer</span>) &#123;
        <span class="hljs-keyword">self</span>.x <span class="hljs-operator">=</span> x
        <span class="hljs-keyword">self</span>.y <span class="hljs-operator">=</span> y
        <span class="hljs-keyword">self</span>.radius <span class="hljs-operator">=</span> radius
        <span class="hljs-keyword">self</span>.drawer <span class="hljs-operator">=</span> drawer
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">draw</span>() &#123;
        drawer.draw(x: x, y: y, radius: radius)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Circle</span>: <span class="hljs-title class_">Shape</span> &#123;
    <span class="hljs-keyword">convenience</span> <span class="hljs-keyword">init</span>(<span class="hljs-params">x</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">y</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">radius</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-keyword">self</span>.<span class="hljs-keyword">init</span>(x: x, y: y, radius: radius, drawer: <span class="hljs-type">CircleDrawer</span>())
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Square</span>: <span class="hljs-title class_">Shape</span> &#123;
    <span class="hljs-keyword">convenience</span> <span class="hljs-keyword">init</span>(<span class="hljs-params">x</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">y</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">radius</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-keyword">self</span>.<span class="hljs-keyword">init</span>(x: x, y: y, radius: radius, drawer: <span class="hljs-type">SquareDrawer</span>())
    &#125;
&#125;

<span class="hljs-keyword">let</span> circle <span class="hljs-operator">=</span> <span class="hljs-type">Circle</span>(x: <span class="hljs-number">10</span>, y: <span class="hljs-number">20</span>, radius: <span class="hljs-number">5</span>)
<span class="hljs-keyword">let</span> square <span class="hljs-operator">=</span> <span class="hljs-type">Square</span>(x: <span class="hljs-number">30</span>, y: <span class="hljs-number">40</span>, radius: <span class="hljs-number">5</span>)

circle.draw()
square.draw()
</code></pre></div></li>
</ul>
<p>在上面的示例中，**<code>Drawer</code>** 接口定义了绘制图形的基本操作，**<code>CircleDrawer</code>** 和 <strong><code>SquareDrawer</code></strong> 则是具体的绘制实现。**<code>Shape</code>** 类则代表图形对象，它包含了一个 <strong><code>Drawer</code></strong> 类型的属性，用于绘制该图形对象。**<code>Circle</code>** 和 <strong><code>Square</code></strong> 类是具体的图形类型，它们继承自 <strong><code>Shape</code></strong> 类，并在初始化时传入不同的绘制实现。</p>
<p>最后当需要创建多个平行的类层次结构，其中一个是实现平台相关代码，另一个是提供跨平台的通用接口，而且这些类层次结构之间的联系需要在运行时建立时，就可以考虑使用桥接模式。</p>
<p>桥接模式的核心思想是将抽象部分与其实现部分分离，以便它们可以独立变化。它允许抽象部分与其实现部分独立扩展，从而提高了系统的可扩展性和灵活性。在桥接模式中，抽象部分通常是指一个抽象类或接口，实现部分通常是指一个具体类。</p>
<p>举个例子，假设我们要设计一个跨平台的绘图软件，支持在不同的操作系统上运行，并且支持不同的绘图形式。我们可以使用桥接模式来设计这个软件，将绘图形式和操作系统分别作为抽象和实现，从而允许在运行时动态地组合不同的抽象和实现。</p>
<p>以下是一个简单的使用桥接模式的 Swift 5 代码示例：</p>
<ul>
<li><p>Swift Code</p>
  <div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">protocol</span> <span class="hljs-title class_">DrawingAPI</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">drawCircle</span>(<span class="hljs-params">x</span>: <span class="hljs-type">Int</span>, <span class="hljs-params">y</span>: <span class="hljs-type">Int</span>, <span class="hljs-params">radius</span>: <span class="hljs-type">Int</span>)
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">DrawingAPI1</span>: <span class="hljs-title class_">DrawingAPI</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">drawCircle</span>(<span class="hljs-params">x</span>: <span class="hljs-type">Int</span>, <span class="hljs-params">y</span>: <span class="hljs-type">Int</span>, <span class="hljs-params">radius</span>: <span class="hljs-type">Int</span>) &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;API1.circle at (<span class="hljs-subst">\(x)</span>:<span class="hljs-subst">\(y)</span>) radius <span class="hljs-subst">\(radius)</span>&quot;</span>)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">DrawingAPI2</span>: <span class="hljs-title class_">DrawingAPI</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">drawCircle</span>(<span class="hljs-params">x</span>: <span class="hljs-type">Int</span>, <span class="hljs-params">y</span>: <span class="hljs-type">Int</span>, <span class="hljs-params">radius</span>: <span class="hljs-type">Int</span>) &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;API2.circle at (<span class="hljs-subst">\(x)</span>:<span class="hljs-subst">\(y)</span>) radius <span class="hljs-subst">\(radius)</span>&quot;</span>)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Shape</span> &#123;
    <span class="hljs-keyword">var</span> drawingAPI: <span class="hljs-type">DrawingAPI</span>?

    <span class="hljs-keyword">init</span>(<span class="hljs-params">drawingAPI</span>: <span class="hljs-type">DrawingAPI</span>) &#123;
        <span class="hljs-keyword">self</span>.drawingAPI <span class="hljs-operator">=</span> drawingAPI
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">draw</span>() &#123;
        <span class="hljs-built_in">preconditionFailure</span>(<span class="hljs-string">&quot;This method must be overridden&quot;</span>)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">CircleShape</span>: <span class="hljs-title class_">Shape</span> &#123;
    <span class="hljs-keyword">var</span> x: <span class="hljs-type">Int</span>
    <span class="hljs-keyword">var</span> y: <span class="hljs-type">Int</span>
    <span class="hljs-keyword">var</span> radius: <span class="hljs-type">Int</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">x</span>: <span class="hljs-type">Int</span>, <span class="hljs-params">y</span>: <span class="hljs-type">Int</span>, <span class="hljs-params">radius</span>: <span class="hljs-type">Int</span>, <span class="hljs-params">drawingAPI</span>: <span class="hljs-type">DrawingAPI</span>) &#123;
        <span class="hljs-keyword">self</span>.x <span class="hljs-operator">=</span> x
        <span class="hljs-keyword">self</span>.y <span class="hljs-operator">=</span> y
        <span class="hljs-keyword">self</span>.radius <span class="hljs-operator">=</span> radius
        <span class="hljs-keyword">super</span>.<span class="hljs-keyword">init</span>(drawingAPI: drawingAPI)
    &#125;

    <span class="hljs-keyword">override</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">draw</span>() &#123;
        drawingAPI<span class="hljs-operator">?</span>.drawCircle(x: x, y: y, radius: radius)
    &#125;
&#125;

<span class="hljs-keyword">let</span> shapes <span class="hljs-operator">=</span> [
    <span class="hljs-type">CircleShape</span>(x: <span class="hljs-number">1</span>, y: <span class="hljs-number">2</span>, radius: <span class="hljs-number">3</span>, drawingAPI: <span class="hljs-type">DrawingAPI1</span>()),
    <span class="hljs-type">CircleShape</span>(x: <span class="hljs-number">5</span>, y: <span class="hljs-number">7</span>, radius: <span class="hljs-number">11</span>, drawingAPI: <span class="hljs-type">DrawingAPI2</span>()),
]

<span class="hljs-keyword">for</span> shape <span class="hljs-keyword">in</span> shapes &#123;
    shape.draw()
&#125;</code></pre></div></li>
</ul>
<p>在上面的代码中，我们首先定义了一个名为 <strong><code>DrawingAPI</code></strong> 的抽象类或接口，该类包含了一个名为 <strong><code>drawCircle</code></strong> 的抽象方法。然后，我们分别实现了 <strong><code>DrawingAPI1</code></strong> 和 <strong><code>DrawingAPI2</code></strong> 这两个具体类，它们分别表示不同的绘图 API。</p>
<h3 id="3-组合模式（Composite-Pattern）"><a href="#3-组合模式（Composite-Pattern）" class="headerlink" title="3. 组合模式（Composite Pattern）"></a>3. 组合模式（Composite Pattern）</h3><p>组合模式（Composite Pattern）是一种结构型设计模式，它允许你将对象组合成树形结构，以表示”部分-整体”的层次关系。组合模式可以让客户端统一处理单个对象和组合对象，从而简化代码。</p>
<p>组合模式通常用于以下场景：</p>
<ul>
<li>需要表示对象的层次结构，且每个对象都具有相同的接口。</li>
<li>需要统一处理单个对象和组合对象，而不需要显式区分它们。</li>
<li>需要对对象进行递归组合，从而能够处理复杂的树形结构。</li>
</ul>
<p>下面是使用 Swift 5 实现组合模式的示例代码：</p>
<ul>
<li><p>Swift Code</p>
  <div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Component</span> &#123;
    <span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span> &#123; <span class="hljs-keyword">get</span> &#125;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">component</span>: <span class="hljs-type">Component</span>)
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">remove</span>(<span class="hljs-params">component</span>: <span class="hljs-type">Component</span>)
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">display</span>(<span class="hljs-params">depth</span>: <span class="hljs-type">Int</span>)
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Leaf</span>: <span class="hljs-title class_">Component</span> &#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> _name: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span> &#123;
        <span class="hljs-keyword">return</span> _name
    &#125;

    <span class="hljs-keyword">init</span>(<span class="hljs-params">name</span>: <span class="hljs-type">String</span>) &#123;
        _name <span class="hljs-operator">=</span> name
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">component</span>: <span class="hljs-type">Component</span>) &#123;
        <span class="hljs-comment">// Leaf 类型不能添加子节点，因此不需要实现该方法</span>
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">remove</span>(<span class="hljs-params">component</span>: <span class="hljs-type">Component</span>) &#123;
        <span class="hljs-comment">// Leaf 类型不能删除子节点，因此不需要实现该方法</span>
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">display</span>(<span class="hljs-params">depth</span>: <span class="hljs-type">Int</span>) &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-type">String</span>(repeating: <span class="hljs-string">&quot;-&quot;</span>, count: depth) <span class="hljs-operator">+</span> <span class="hljs-string">&quot; &quot;</span> <span class="hljs-operator">+</span> name)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Composite</span>: <span class="hljs-title class_">Component</span> &#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> _name: <span class="hljs-type">String</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> _children <span class="hljs-operator">=</span> [<span class="hljs-type">Component</span>]()

    <span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span> &#123;
        <span class="hljs-keyword">return</span> _name
    &#125;

    <span class="hljs-keyword">init</span>(<span class="hljs-params">name</span>: <span class="hljs-type">String</span>) &#123;
        _name <span class="hljs-operator">=</span> name
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">component</span>: <span class="hljs-type">Component</span>) &#123;
        _children.append(component)
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">remove</span>(<span class="hljs-params">component</span>: <span class="hljs-type">Component</span>) &#123;
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> index <span class="hljs-operator">=</span> _children.firstIndex(where: &#123; <span class="hljs-variable">$0</span> <span class="hljs-operator">===</span> component &#125;) &#123;
            _children.remove(at: index)
        &#125;
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">display</span>(<span class="hljs-params">depth</span>: <span class="hljs-type">Int</span>) &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-type">String</span>(repeating: <span class="hljs-string">&quot;-&quot;</span>, count: depth) <span class="hljs-operator">+</span> <span class="hljs-string">&quot; &quot;</span> <span class="hljs-operator">+</span> name)
        _children.forEach &#123; <span class="hljs-variable">$0</span>.display(depth: depth <span class="hljs-operator">+</span> <span class="hljs-number">2</span>) &#125;
    &#125;
&#125;

<span class="hljs-comment">// 使用示例</span>
<span class="hljs-keyword">let</span> root <span class="hljs-operator">=</span> <span class="hljs-type">Composite</span>(name: <span class="hljs-string">&quot;root&quot;</span>)
root.add(component: <span class="hljs-type">Leaf</span>(name: <span class="hljs-string">&quot;Leaf A&quot;</span>))
root.add(component: <span class="hljs-type">Leaf</span>(name: <span class="hljs-string">&quot;Leaf B&quot;</span>))

<span class="hljs-keyword">let</span> compositeX <span class="hljs-operator">=</span> <span class="hljs-type">Composite</span>(name: <span class="hljs-string">&quot;Composite X&quot;</span>)
compositeX.add(component: <span class="hljs-type">Leaf</span>(name: <span class="hljs-string">&quot;Leaf XA&quot;</span>))
compositeX.add(component: <span class="hljs-type">Leaf</span>(name: <span class="hljs-string">&quot;Leaf XB&quot;</span>))
root.add(component: compositeX)

<span class="hljs-keyword">let</span> compositeY <span class="hljs-operator">=</span> <span class="hljs-type">Composite</span>(name: <span class="hljs-string">&quot;Composite Y&quot;</span>)
compositeY.add(component: <span class="hljs-type">Leaf</span>(name: <span class="hljs-string">&quot;Leaf YA&quot;</span>))
compositeY.add(component: <span class="hljs-type">Leaf</span>(name: <span class="hljs-string">&quot;Leaf YB&quot;</span>))
compositeX.add(component: compositeY)

root.display(depth: <span class="hljs-number">1</span>)</code></pre></div></li>
</ul>
<p>在这个示例中，**<code>Component</code>** 是组合模式的抽象基类，包含了所有叶子节点和组合节点都具有的方法和属性。**<code>Leaf</code>** 是叶子节点的具体实现，它不能添加子节点。**<code>Composite</code>** 是组合节点的具体实现，它可以添加和删除子节点，并递归调用子节点的 <strong><code>display</code></strong> 方法。</p>
<h3 id="4-装饰模式（Decorator-Pattern）"><a href="#4-装饰模式（Decorator-Pattern）" class="headerlink" title="4. 装饰模式（Decorator Pattern）"></a>4. 装饰模式（Decorator Pattern）</h3><p>装饰模式（Decorator Pattern）是一种结构型设计模式，它允许你在不改变对象自身的基础上动态地给对象添加新的行为。它通常被用来解决在不改变现有代码的情况下，动态地给对象添加新的功能或行为。</p>
<p>装饰模式的核心思想是在运行时通过一系列的装饰器包裹原始对象来实现功能的添加。每个装饰器都与被包裹的对象实现相同的接口，因此可以在不修改原始对象的情况下添加新的行为。</p>
<p>下面是一个使用 Swift 5 实现装饰模式的例子，假设我们有一个 <strong><code>Beverage</code></strong> 协议表示饮料，我们想要给饮料添加调料的功能，我们可以使用装饰模式来实现：</p>
<ul>
<li><p>Swift Code</p>
  <div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-comment">// 饮料协议</span>
<span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Beverage</span> &#123;
    <span class="hljs-keyword">var</span> description: <span class="hljs-type">String</span> &#123; <span class="hljs-keyword">get</span> &#125;
    <span class="hljs-keyword">var</span> cost: <span class="hljs-type">Double</span> &#123; <span class="hljs-keyword">get</span> &#125;
&#125;

<span class="hljs-comment">// 浓缩咖啡类</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Espresso</span>: <span class="hljs-title class_">Beverage</span> &#123;
    <span class="hljs-keyword">var</span> description: <span class="hljs-type">String</span> &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Espresso&quot;</span>
    &#125;
    <span class="hljs-keyword">var</span> cost: <span class="hljs-type">Double</span> &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-number">1.99</span>
    &#125;
&#125;

<span class="hljs-comment">// 调料装饰器基类</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">CondimentDecorator</span>: <span class="hljs-title class_">Beverage</span> &#123;
    <span class="hljs-keyword">let</span> beverage: <span class="hljs-type">Beverage</span>
    <span class="hljs-keyword">var</span> description: <span class="hljs-type">String</span> &#123;
        <span class="hljs-keyword">return</span> beverage.description
    &#125;
    <span class="hljs-keyword">var</span> cost: <span class="hljs-type">Double</span> &#123;
        <span class="hljs-keyword">return</span> beverage.cost
    &#125;
    <span class="hljs-keyword">init</span>(<span class="hljs-keyword">_</span> <span class="hljs-params">beverage</span>: <span class="hljs-type">Beverage</span>) &#123;
        <span class="hljs-keyword">self</span>.beverage <span class="hljs-operator">=</span> beverage
    &#125;
&#125;

<span class="hljs-comment">// 摩卡调料装饰器</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Mocha</span>: <span class="hljs-title class_">CondimentDecorator</span> &#123;
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">var</span> description: <span class="hljs-type">String</span> &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;<span class="hljs-subst">\(beverage.description)</span>, Mocha&quot;</span>
    &#125;
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">var</span> cost: <span class="hljs-type">Double</span> &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-number">0.20</span> <span class="hljs-operator">+</span> beverage.cost
    &#125;
&#125;

<span class="hljs-comment">// 奶泡调料装饰器</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Whip</span>: <span class="hljs-title class_">CondimentDecorator</span> &#123;
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">var</span> description: <span class="hljs-type">String</span> &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;<span class="hljs-subst">\(beverage.description)</span>, Whip&quot;</span>
    &#125;
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">var</span> cost: <span class="hljs-type">Double</span> &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-number">0.10</span> <span class="hljs-operator">+</span> beverage.cost
    &#125;
&#125;</code></pre></div></li>
</ul>
<p>在上面的例子中，**<code>Beverage</code>** 协议定义了一个饮料的接口，其中包含一个 <strong><code>description</code></strong> 属性表示饮料的描述和一个 <strong><code>cost</code></strong> 属性表示饮料的价格。**<code>Espresso</code>** 类是一种饮料，实现了 <strong><code>Beverage</code></strong> 协议。</p>
<p><strong><code>CondimentDecorator</code></strong> 类是装饰器的基类，实现了 <strong><code>Beverage</code></strong> 协议，它包含一个指向被装饰的饮料的引用，并且提供了默认的 <strong><code>description</code></strong> 和 <strong><code>cost</code></strong> 实现。**<code>Mocha</code>** 和 <strong><code>Whip</code></strong> 类是具体的装饰器类，它们继承自 <strong><code>CondimentDecorator</code></strong> 并且实现了自己的 <strong><code>description</code></strong> 和 <strong><code>cost</code></strong> 方法来添加新的行为。</p>
<p>使用装饰模式，我们可以像下面这样使用装饰器来装饰原始的饮料对象：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">let</span> beverage: <span class="hljs-type">Beverage</span> <span class="hljs-operator">=</span> <span class="hljs-type">Espresso</span>()
<span class="hljs-comment">//现在我们已经创建了一个 Espresso 饮料对象，接下来我们可以使用 Mocha 和 Whip 装饰器来添加新的行为：</span>
<span class="hljs-keyword">let</span> mocha: <span class="hljs-type">Beverage</span> <span class="hljs-operator">=</span> <span class="hljs-type">Mocha</span>(beverage)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;<span class="hljs-subst">\(mocha.description)</span> $<span class="hljs-subst">\(mocha.cost)</span>&quot;</span>)

<span class="hljs-keyword">let</span> whip: <span class="hljs-type">Beverage</span> <span class="hljs-operator">=</span> <span class="hljs-type">Whip</span>(mocha)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;<span class="hljs-subst">\(whip.description)</span> $<span class="hljs-subst">\(whip.cost)</span>&quot;</span>)</code></pre></div>

<p>在上面的代码中，我们先用 <strong><code>Mocha</code></strong> 装饰器包裹了原始的 <strong><code>Espresso</code></strong> 对象，然后使用 <strong><code>Whip</code></strong> 装饰器包裹了 <strong><code>Mocha</code></strong> 对象。最终，我们得到了一个包含 <strong><code>Espresso</code><strong>、</strong><code>Mocha</code></strong> 和 <strong><code>Whip</code></strong> 的新的饮料对象，并且可以输出其描述和价格。</p>
<p>装饰器模式的优点在于它允许你在不改变原始对象的情况下，动态地添加新的行为。这使得代码更加灵活，因为你可以通过组合不同的装饰器来创建各种不同的对象。另外，装饰器模式还遵循开闭原则，因为你可以添加新的装饰器而不必修改现有的代码。</p>
<p>当然，装饰器模式并不适用于所有情况。如果你需要对对象进行大量的装饰操作，可能会导致代码变得难以维护。此外，在某些情况下，可能更好的解决方案是使用继承来扩展对象的功能，而不是使用装饰器模式。</p>
<h3 id="5-外观模式（Facade-Pattern）"><a href="#5-外观模式（Facade-Pattern）" class="headerlink" title="5. 外观模式（Facade Pattern）"></a>5. 外观模式（Facade Pattern）</h3><p>外观模式（Facade Pattern）是一种设计模式，它提供了一个简单的接口，用于隐藏复杂系统的复杂性。它的主要目的是为客户端代码提供一个简单的接口，使其可以访问复杂系统的功能，而不需要了解系统的内部实现细节。</p>
<p>外观模式通常用于以下情况：</p>
<ul>
<li>当一个系统的复杂性使得它的实现变得困难时，可以使用外观模式来简化接口。</li>
<li>当需要将一个复杂系统划分为更小的子系统时，可以使用外观模式来创建更简单的接口。</li>
</ul>
<p>以下是一个使用 Swift 5 实现外观模式的示例：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-comment">// 复杂系统的子系统</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">SubsystemA</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">operationA</span>() -&gt; <span class="hljs-type">String</span> &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Subsystem A operation&quot;</span>
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">SubsystemB</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">operationB</span>() -&gt; <span class="hljs-type">String</span> &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Subsystem B operation&quot;</span>
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">SubsystemC</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">operationC</span>() -&gt; <span class="hljs-type">String</span> &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Subsystem C operation&quot;</span>
    &#125;
&#125;

<span class="hljs-comment">// 定义外观接口</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Facade</span> &#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> subsystemA <span class="hljs-operator">=</span> <span class="hljs-type">SubsystemA</span>()
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> subsystemB <span class="hljs-operator">=</span> <span class="hljs-type">SubsystemB</span>()
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> subsystemC <span class="hljs-operator">=</span> <span class="hljs-type">SubsystemC</span>()

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">operation</span>() -&gt; <span class="hljs-type">String</span> &#123;
        <span class="hljs-keyword">var</span> result <span class="hljs-operator">=</span> <span class="hljs-string">&quot;Facade initializes subsystems:<span class="hljs-subst">\n</span>&quot;</span>
        result <span class="hljs-operator">+=</span> subsystemA.operationA()
        result <span class="hljs-operator">+=</span> subsystemB.operationB()
        result <span class="hljs-operator">+=</span> subsystemC.operationC()
        <span class="hljs-keyword">return</span> result
    &#125;
&#125;

<span class="hljs-comment">// 客户端代码使用外观接口</span>
<span class="hljs-keyword">let</span> facade <span class="hljs-operator">=</span> <span class="hljs-type">Facade</span>()
<span class="hljs-built_in">print</span>(facade.operation())</code></pre></div>

<p>在这个示例中，**<code>SubsystemA</code><strong>、</strong><code>SubsystemB</code>** 和 <strong><code>SubsystemC</code></strong> 是一个复杂系统的三个子系统。**<code>Facade</code>** 提供了一个简单的接口来初始化这些子系统，并在客户端代码中使用。客户端代码只需要使用 <strong><code>Facade</code></strong> 对象的 <strong><code>operation()</code></strong> 方法来调用子系统的操作，而不需要了解每个子系统的内部实现细节。</p>
<h3 id="6-享元模式（Flyweight-Pattern）"><a href="#6-享元模式（Flyweight-Pattern）" class="headerlink" title="6. 享元模式（Flyweight Pattern）"></a>6. 享元模式（Flyweight Pattern）</h3><p>享元模式（Flyweight Pattern）是一种设计模式，它通过共享相似对象来最小化内存使用和提高性能。这个模式适用于需要创建大量对象的情况，但又不想消耗过多内存的场景。</p>
<p>具体来说，享元模式的核心思想是将对象分为两部分：内部状态（Intrinsic State）和外部状态（Extrinsic State）。其中，内部状态是可以共享的，外部状态是根据需要变化的。这样，在创建对象时，只需创建一部分对象并将其共享，可以显著减少内存消耗。</p>
<p>在实际应用中，享元模式经常用于优化大规模数据处理、图形渲染等领域。</p>
<p>下面是使用 Swift 5 实现享元模式的示例代码：</p>
<ul>
<li><p>Swift Code</p>
  <div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-comment">// 定义享元协议</span>
<span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Flyweight</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">operation</span>(<span class="hljs-params">extrinsicState</span>: <span class="hljs-type">Int</span>)
&#125;

<span class="hljs-comment">// 具体享元类</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">ConcreteFlyweight</span>: <span class="hljs-title class_">Flyweight</span> &#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> intrinsicState: <span class="hljs-type">String</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">intrinsicState</span>: <span class="hljs-type">String</span>) &#123;
        <span class="hljs-keyword">self</span>.intrinsicState <span class="hljs-operator">=</span> intrinsicState
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">operation</span>(<span class="hljs-params">extrinsicState</span>: <span class="hljs-type">Int</span>) &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Intrinsic state: <span class="hljs-subst">\(intrinsicState)</span>, Extrinsic state: <span class="hljs-subst">\(extrinsicState)</span>&quot;</span>)
    &#125;
&#125;

<span class="hljs-comment">// 享元工厂</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">FlyweightFactory</span> &#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> flyweights <span class="hljs-operator">=</span> [<span class="hljs-type">String</span>: <span class="hljs-type">Flyweight</span>]()

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">getFlyweight</span>(<span class="hljs-params">intrinsicState</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Flyweight</span> &#123;
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> flyweight <span class="hljs-operator">=</span> flyweights[intrinsicState] &#123;
            <span class="hljs-keyword">return</span> flyweight
        &#125; <span class="hljs-keyword">else</span> &#123;
            <span class="hljs-keyword">let</span> flyweight <span class="hljs-operator">=</span> <span class="hljs-type">ConcreteFlyweight</span>(intrinsicState: intrinsicState)
            flyweights[intrinsicState] <span class="hljs-operator">=</span> flyweight
            <span class="hljs-keyword">return</span> flyweight
        &#125;
    &#125;
&#125;

<span class="hljs-comment">// 使用享元模式</span>
<span class="hljs-keyword">let</span> factory <span class="hljs-operator">=</span> <span class="hljs-type">FlyweightFactory</span>()
<span class="hljs-keyword">let</span> flyweight1 <span class="hljs-operator">=</span> factory.getFlyweight(intrinsicState: <span class="hljs-string">&quot;A&quot;</span>)
flyweight1.operation(extrinsicState: <span class="hljs-number">1</span>) <span class="hljs-comment">// Intrinsic state: A, Extrinsic state: 1</span>

<span class="hljs-keyword">let</span> flyweight2 <span class="hljs-operator">=</span> factory.getFlyweight(intrinsicState: <span class="hljs-string">&quot;B&quot;</span>)
flyweight2.operation(extrinsicState: <span class="hljs-number">2</span>) <span class="hljs-comment">// Intrinsic state: B, Extrinsic state: 2</span>

<span class="hljs-keyword">let</span> flyweight3 <span class="hljs-operator">=</span> factory.getFlyweight(intrinsicState: <span class="hljs-string">&quot;A&quot;</span>)
flyweight3.operation(extrinsicState: <span class="hljs-number">3</span>) <span class="hljs-comment">// Intrinsic state: A, Extrinsic state: 3</span></code></pre></div></li>
</ul>
<p>在上面的示例中，我们定义了一个 <strong><code>Flyweight</code></strong> 协议，具体享元类 <strong><code>ConcreteFlyweight</code></strong> 实现了这个协议。**<code>FlyweightFactory</code>** 是享元工厂类，用于创建和管理享元对象。在使用时，我们可以通过工厂类获取享元对象，并在其中设置外部状态。由于相同的内部状态只会被创建一次，因此 <strong><code>flyweight1</code></strong> 和 <strong><code>flyweight3</code></strong> 实际上是同一个对象，可以共享使用。</p>
<h3 id="7-代理模式（Proxy-Pattern）"><a href="#7-代理模式（Proxy-Pattern）" class="headerlink" title="7. 代理模式（Proxy Pattern）"></a>7. 代理模式（Proxy Pattern）</h3><p>代理模式是一种结构型设计模式，它允许你提供一个代理对象来控制对另一个对象的访问。</p>
<p>代理对象充当原始对象的接口，它可以处理客户端的请求并在必要时将请求传递给原始对象。代理模式常用于以下场景：</p>
<ul>
<li>远程代理：允许客户端通过网络访问远程对象，例如远程服务API。</li>
<li>虚拟代理：在需要时创建开销很大的对象，例如一个大型图片或者视频对象。</li>
<li>保护代理：控制对敏感对象的访问，例如在用户没有权限的情况下禁止修改数据。</li>
</ul>
<p>下面是一个使用 Swift 5 代码实现虚拟代理的示例：</p>
<ul>
<li><p>Swift Code</p>
  <div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Image</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">display</span>()
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">RealImage</span>: <span class="hljs-title class_">Image</span> &#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> fileName: <span class="hljs-type">String</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">fileName</span>: <span class="hljs-type">String</span>) &#123;
        <span class="hljs-keyword">self</span>.fileName <span class="hljs-operator">=</span> fileName
        loadFromDisk()
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">display</span>() &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Displaying <span class="hljs-subst">\(fileName)</span>&quot;</span>)
    &#125;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">loadFromDisk</span>() &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Loading <span class="hljs-subst">\(fileName)</span> from disk&quot;</span>)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">ImageProxy</span>: <span class="hljs-title class_">Image</span> &#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> realImage: <span class="hljs-type">RealImage</span>?
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> fileName: <span class="hljs-type">String</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">fileName</span>: <span class="hljs-type">String</span>) &#123;
        <span class="hljs-keyword">self</span>.fileName <span class="hljs-operator">=</span> fileName
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">display</span>() &#123;
        <span class="hljs-keyword">if</span> realImage <span class="hljs-operator">==</span> <span class="hljs-literal">nil</span> &#123;
            realImage <span class="hljs-operator">=</span> <span class="hljs-type">RealImage</span>(fileName: fileName)
        &#125;
        realImage<span class="hljs-operator">?</span>.display()
    &#125;
&#125;

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">let</span> image <span class="hljs-operator">=</span> <span class="hljs-type">ImageProxy</span>(fileName: <span class="hljs-string">&quot;test.jpg&quot;</span>)
image.display()</code></pre></div></li>
</ul>
<p>在这个示例中，**<code>RealImage</code>** 类表示一个真实的图片对象，它负责加载和显示图片。**<code>ImageProxy</code>** 类则是一个代理，它代表了一个 <strong><code>RealImage</code></strong> 对象并控制了对它的访问。当 <strong><code>ImageProxy</code></strong> 对象的 <strong><code>display</code></strong> 方法被调用时，它会先检查 <strong><code>realImage</code></strong> 是否已经存在。如果 <strong><code>realImage</code></strong> 不存在，那么它会创建一个 <strong><code>RealImage</code></strong> 对象并将其存储在 <strong><code>realImage</code></strong> 中，然后调用 <strong><code>display</code></strong> 方法。如果 <strong><code>realImage</code></strong> 已经存在，那么它将直接调用 <strong><code>realImage</code></strong> 的 <strong><code>display</code></strong> 方法。</p>
<p>这个示例展示了代理模式如何允许你使用代理对象来控制对另一个对象的访问。在这个示例中，**<code>ImageProxy</code>** 充当了 <strong><code>RealImage</code></strong> 的接口，并在必要时创建了一个 <strong><code>RealImage</code></strong> 对象。这使得客户端无需知道 <strong><code>RealImage</code></strong> 的实际细节，从而简化了系统的设计。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" class="category-chain-item">设计模式</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">#设计模式</a>
      
        <a href="/tags/Swift/">#Swift</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>24 种设计模式-2 (Swift 5版)</div>
      <div>https://icoobin.github.io/2023/02/25/other/24-种设计模式-2-Swift-5版/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>程守斌</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年2月25日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/02/25/other/24-%E7%A7%8D%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-1-Swift-5%E7%89%88/" title="24 种设计模式-1 (Swift 5版)">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">24 种设计模式-1 (Swift 5版)</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/02/25/other/24-%E7%A7%8D%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-3-Swift-5%E7%89%88/" title="24 种设计模式-3 (Swift 5版)">
                        <span class="hidden-mobile">24 种设计模式-3 (Swift 5版)</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
      <div class="col-lg-7 mx-auto nopadding-x-md">
        <div class="container custom mx-auto">
           <script src="/js/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script> <script>L2Dwidget.init({ pluginRootPath: "live2dw/", pluginJsPath: "lib/", pluginModelPath: "assets/", tagMode: !1, log: !1, model: { jsonPath: "/js/live2dw/assets/hijiki.model.json" }, display: { position: "left", hOffset: 60, vOffset: 0, width: 150, height: 300 }, mobile: { show: !1 } })</script> 
        </div>
      </div>
    
  </main>

  <footer>
    <div class="footer-inner">
    
        <div class="footer-content">
             <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
        </div>
        
            
                <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

                    
                        
                                    
</div>

<!-- <script src="js/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script>
<script>L2Dwidget.init({ pluginRootPath: "live2dw/", pluginJsPath: "lib/", pluginModelPath: "assets/", tagMode: !1, log: !1, model: { jsonPath: "js/live2dw/assets/hijiki.model.json" }, display: { position: "left", hOffset: 60, vOffset: 0, width: 150, height: 300 }, mobile: { show: !1 } })</script> -->

<!--
<div id="music_div" style="position: fixed; bottom: 0px; left: 30px;">
    <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=110
        src="//music.163.com/outchain/player?type=0&id=919444742&auto=1&height=90">
    </iframe>
    <script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
    <script src="/js/musicshow.js"></script>
</div>
-->

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
